package tt.love.hw.common.config;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class ActionConfig {
    private Map<String, FormBean> forms = new HashMap<String, FormBean>();
    private Map<String, ActionBean> actions = new HashMap<String, ActionBean>();

    public ActionConfig(InputStream in) {
        init(in);
    }

    public void init(InputStream in) {
        Digester digester = new Digester();
        digester.push(this);
        digester.setValidating(false);
        digester.addObjectCreate("action-config/forms/form", FormBean.class);
        digester.addSetProperties("action-config/forms/form");
        digester.addObjectCreate("action-config/forms/form/property", FormBeanProperty.class);
        digester.addSetProperties("action-config/forms/form/property");
        digester.addSetNext("action-config/forms/form/property", "addProperty");
        digester.addSetNext("action-config/forms/form", "addFormBean");
        digester.addObjectCreate("action-config/actions/action", ActionBean.class);
        digester.addSetProperties("action-config/actions/action");
        digester.addSetNext("action-config/actions/action", "addActionBean");
        try {
            digester.parse(in);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    public Map<String, FormBean> getForms() {
        return forms;
    }

    public void setForms(Map<String, FormBean> forms) {
        this.forms = forms;
    }

    public void addFormBean(FormBean formBean) {
        forms.put(formBean.getId(), formBean);
    }

    public Map<String, ActionBean> getActions() {
        return actions;
    }

    public void setActions(Map<String, ActionBean> actions) {
        this.actions = actions;
    }

    public void addActionBean(ActionBean actionBean) {
        actions.put(actionBean.getPath(), actionBean);
    }


    @Override
    public String toString() {
        return "ActionConfig{" +
                "forms=" + forms +
                ", actions=" + actions +
                '}';
    }
}
